package com.pangda.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pangda.common.domain.PageResult;
import com.pangda.common.domain.ResponseResult;
import com.pangda.common.utils.FileUtil;
import com.pangda.pojo.OperationLog;
import com.pangda.pojo.data.OperationLogData;
import com.pangda.service.IOperationLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 操作日志表 前端控制器
 * </p>
 *
 * @author xjy
 * @since 2024-06-22
 */
@RestController
@RequestMapping("/monitor/operlog")
@Api(tags = "操作日志管理")
public class OperationLogController {
    @Autowired
    private IOperationLogService operationLogService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("操作日志列表")
    public PageResult list(PageResult pageResult, String keyWord) {
        String beginTime = null;
        String endTime = null;
        if (ObjectUtil.isNotEmpty(pageResult.getParams())) {
            beginTime = (String) pageResult.getParams().get("beginTime");
            endTime = (String) pageResult.getParams().get("endTime");
        }

        Page<OperationLog> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        LambdaQueryWrapper<OperationLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(keyWord), OperationLog::getOperUrl, keyWord)
                .between(ObjectUtil.isNotEmpty(beginTime) && ObjectUtil.isNotEmpty(endTime), OperationLog::getOperTime, beginTime, endTime)
                .orderByDesc(OperationLog::getOperTime);
        operationLogService.page(page, queryWrapper);
        return PageResult.success(page, OperationLog.class);
    }

    @DeleteMapping("/{operIds}")
    @ApiOperation("删除操作日志")
    public ResponseResult delete(@PathVariable List<Integer> operIds) {
        if (operIds.isEmpty()) {
            return ResponseResult.error("请选择要删除的数据");
        }
        operationLogService.removeByIds(operIds);
        return ResponseResult.success();
    }

    @DeleteMapping("/clean")
    @ApiOperation("清空操作日志")
    public ResponseResult clean() {
        operationLogService.remove(null);
        return ResponseResult.success();
    }

    @GetMapping("/export")
    @ApiOperation("导出操作日志")
    public Map<String, String> export() throws Exception {
        List<OperationLog> list = operationLogService.list();
        return FileUtil.uploadFile(list, OperationLogData.class, redisTemplate);
    }
}
